package cn.bdqn.controller;

import cn.bdqn.entity.Student;
import cn.bdqn.service.StudentService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @author zhangpengxiang
 * @description TODO
 * @date 2024/7/12
 */
@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/update")
    public String toUpdate(Integer id,Model model){
        Student stu = studentService.getStudentById(id);
        model.addAttribute("stu",stu);
        return "studentUpdate";
    }

    @PostMapping("/update")
    public String update(Student student){
        studentService.updateStudent(student);
        return "redirect:list";
    }

    @PostMapping("/remove")
    @ResponseBody
    public String remove(Integer id){
        studentService.removeStudent(id);
        HashMap<String,Object> data = new HashMap<>();
        data.put("success",1);

        return JSON.toJSONString(data);
    }
    @GetMapping("/add")
    public String toAdd(){
        return "studentAdd";
    }

    @PostMapping("/add")
    public String add(@Valid Student student, BindingResult result, @RequestParam("headImg") MultipartFile headImg, HttpSession session) throws IOException {

        if (result.hasFieldErrors()) {
            throw  new RuntimeException("字段不能为空！");
        }


        //实现文件上传
        //上传文件目录
        String uploadPath = session.getServletContext().getRealPath("/upload");
        File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()){
            uploadFile.mkdirs();
        }
        //对文件进行重命名   当前系统时间毫秒数+后缀
        long time = System.currentTimeMillis();
        String suffix = headImg.getOriginalFilename().substring(headImg.getOriginalFilename().lastIndexOf("."));
        //新的文件名称
        String newFileName = time + suffix;
        student.setHeadImgPath(newFileName);

        //上传

        headImg.transferTo(new File(uploadPath + File.separator + newFileName));


        studentService.addStudent(student);
        return "redirect:/student/list";
    }

    @GetMapping("/list")
    public String toList(@RequestParam(required = false, defaultValue = "1") Integer pageIndex, @RequestParam(required = false, defaultValue = "5") Integer pageSize, String name,String address,Model model) {

        List<Student> studentList = null;

            //分页数据
            studentList = studentService.findAll(pageIndex,pageSize,name,address);
            //总数据量
            int totalCount = studentService.countStudent(name,address);
            //总页数
            int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
            //防止没有数据的时候翻页报错
            if (totalPage == 0){
                totalPage = 1;
            }
            model.addAttribute("totalPage",totalPage);
            //当前页
            model.addAttribute("pageIndex", pageIndex);
            //分页数据
            model.addAttribute("studentList", studentList);

            //回显数据
            model.addAttribute("name",name);
            model.addAttribute("address",address);

        return "studentList";
    }


}
